<?php

namespace app\controller;

use app\model\Stations;
use think\facade\Db;
use think\response\Json;

class Location
{
    public function getLngLat(): Json
    {
        $param = request()->param();
        $url = "https://api.map.baidu.com/geoconv/v2/?coords=$param[lng],$param[lat]&model=1&ak=DFdaVkBdZGv1AOWCP5wMWBk0M6qPxLLS";
        $res = @file_get_contents($url);
        $res = json_decode($res, true);
        if (empty($res) || $res['status'] != 0) return json(['code' => 400, 'msg' => '获取经纬度失败'], 401);
        return json(['code' => 200, 'msg' => '获取经纬度成功', 'data' => $res['result'][0]]);
    }

    public function updateStationLst()
    {
        $model = app(Stations::class);
        $data = $model->select()->toArray();

        $items = array_map(function ($item) {
            if (!is_numeric($item['lng']) || !is_numeric($item['lat'])) {
                return $item; // 跳过无效的经纬度
            }
            // 使用 ST_GeomFromText 创建 POINT 值
            $item['location'] = Db::raw("ST_GeomFromText('POINT({$item['lng']} {$item['lat']})')");
            unset($item['create_time'], $item['update_time']);
            return $item;
        }, $data);
        if (!empty($items)) {
            // 使用 saveAll 方法批量更新数据
            $model->saveAll($items);
        }
    }
}
